<template>
    <div class="stop-stat page-content content full-height">
      <collapse ref="collapse">
        <template v-slot:content>
          <yz-condition-filter
              v-model="queryParams"
              @resetSearch="resetSearch"
              @onSubmit="onSubmit"
              style="margin-top: 4px;"
          >
            <yz-input
                v-model.trim="queryParams.dateRange"
                class="q-mr-md"
                inputType="date"
                :disabledType="notDisableDate"
                hint="选择时间范围"
                isTip
                title="日期"
            ></yz-input>
            <div class="q-mr-md flex q-mb-sm">
              <div class="for-time fontSize-14" style="margin-left: 0px">时长范围(分钟):</div>
              <q-input outlined
                       class="btn-time"
                       dense
                       mask="#######"
                       v-model="queryParams.stopDurationStart" />
              <div class="for-time">~</div>
              <q-input outlined
                       class="btn-time"
                       dense
                       mask="#######"
                       v-model="queryParams.stopDurationEnd" />
            </div>
            <select-tooltip v-model="queryParams.stopTypeIds"
                            multiple
                            :options="equipmentTypeOptions"
                            :msg="`${statusList[1].label}类型`"></select-tooltip>
            <workshop-search v-model="queryParams" ref="workShopSearch" :is-shift="false"/>
          </yz-condition-filter>
          <div class="form-inline bottom" style="padding-bottom: 14px">
              <q-btn class="btn margin-r-10"
                     outline
                     :disable="!tableData.length"
                     color="primary"
                     v-if="!isFillIn"
                     @click="onExcel">
                导出Excel
              </q-btn>
              <q-btn class="btn margin-r-10"
                     outline
                     color="primary"
                     :disable="!selectedReport.length"
                     v-if="isFillIn"
                     @click="onFillin">
                批量填报
              </q-btn>
          </div>
        </template>
      </collapse>
      <!-- table 表格 -->
      <q-table :data="tableData"
               :columns="tableColumns"
               row-key="indexId"
               class="myTable scroll"
               style="padding-top: 6px"
               :pagination.sync="pagination"
               :hide-bottom="!!tableData.length"
               :loading="isTableLoading"
               v-if="!isFillIn"
               color="primary">
        <template v-slot:body-cell-stopCause="props">
          <q-td>
            {{ props.row.stopCause ? props.row.stopCause.length > 30 ? props.row.stopCause.substr(0, 30) + '...' : props.row.stopCause : '--' }}
            <q-tooltip v-if="props.row.stopCause && props.row.stopCause.length > 30">{{props.row.stopCause}}</q-tooltip>
          </q-td>
        </template>
      </q-table>
      <q-table :data="tableData"
               :columns="tableColumns"
               row-key="indexId"
               class="myTable scroll stick-last-col"
               style="padding-top: 6px"
               :pagination.sync="pagination"
               :hide-bottom="!!tableData.length"
               selection="multiple"
               :selected.sync="selectedReport"
               :loading="isTableLoading"
               v-if="isFillIn"
               color="primary">
                <template v-slot:body-cell-operate="props">
                  <q-td class="text-center">
                    <table-btn btn-type="edit" @click="showEditDialog(props.row)"/>
                  </q-td>
                </template>
      </q-table>
      <!-- 分页 -->
      <yz-pagination v-model="pagination" @onSearch="getList"/>
      <!-- 异常明细 -->
      <edit-detail
        :show="editDetail.show"
        :data="editDetail.data"
        :selectedReport="editDetail.selReport"
        :isReports="isReports"
        :isFilter="true"
        @getList="getList()"
        @close="editDetail.show = false"
      />
    </div>
</template>

<script>
import Collapse from 'src/components/collapse'
import _ from 'lodash'
import { date } from 'quasar'
import moment from 'moment'
import editDetail from '../status-monitor-v3/components/edit-detail'
import { getCauseTypeList } from '../../boot/system/reason'
import { getStopStatList, getExportExcel } from '../../boot/statistics/stop-stat'
import { mapGetters } from 'vuex'

export default {
  name: 'stop-stat',
  components: {
    Collapse,
    editDetail
  },
  props: {
    isFillIn: {
      default: false,
      type: Boolean
    }
  },
  data () {
    return {
      searchCondition: [{ id: 'materialsNum', name: '停机人' }],
      requestId: null, // 导出唯一标识
      equipmentTypeOptions: [],
      queryParams: {
        dateRange: [date.subtractFromDate(new Date(), { days: 6 }), new Date()],
        stopTypeIds: ['all'],
        stopDurationStart: null,
        stopDurationEnd: null,
        location: {
          id: null,
          level: null,
          label: '',
          hash: ''
        },
        devices: ['all']
      },
      // table loading
      isTableLoading: false,
      // 表格分页配置
      pagination: {
        // 当前页码
        pageNum: 1,
        // 每页条数
        pageSize: 15,
        // 总条数
        rowsNumber: 0
      },
      // 表格内容
      tableData: [],
      editDetail: {
        show: false,
        data: null,
        selReport: []
      },
      cloneParams: {},
      isReports: false,
      selectedReport: []
    }
  },
  watch: {
    selectedReport (val) {
      if (val.length > 60) {
        this.$q.dialog({
          title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>提示</p>`,
          html: true,
          persistent: true,
          message: '批量填报不超过60条!',
          ok: {
            unelevated: true,
            label: '确认'
          }
        }).onOk(() => {
          this.selectedReport = this.selectedReport.slice(0, 60)
        })
      }
    }
  },
  computed: {
    ...mapGetters([
      'client', 'statusList'
    ]),
    columns () {
      const params = _.cloneDeep(this.tableColumns)
      return params.filter(v => v.name !== 'operate')
    },
    tableColumns () {
      // 表格头部数据
      const tableColumns = [
        {
          name: 'startTime',
          field: 'startTime',
          label: `${this.statusList[1].label}开始时间`,
          align: 'left'
        },
        {
          name: 'endTime',
          field: 'endTime',
          label: `${this.statusList[1].label}结束时间`,
          align: 'left'
        },
        {
          name: 'deviceName',
          field: 'deviceName',
          label: '设备名称(编码)',
          align: 'left'
        },
        {
          name: 'location',
          field: 'location',
          label: '所在位置',
          align: 'left'
        },
        {
          name: 'shiftsName',
          field: 'shiftsName',
          label: `${this.statusList[1].label}班次`,
          align: 'left'
        },
        {
          name: 'productName',
          field: 'productName',
          label: '产品名称',
          align: 'left'
        },
        {
          name: 'productNumber',
          field: 'productNumber',
          label: '产品编号',
          align: 'left'
        },
        {
          name: 'processName',
          field: 'processName',
          label: '加工工序',
          align: 'left'
        },
        { name: 'stopPerson', field: 'stopPerson', label: `${this.statusList[1].label}人`, align: 'left' },
        {
          name: 'stopType',
          field: 'stopType',
          label: `${this.statusList[1].label}类型`,
          align: 'left'
        },
        {
          name: 'stopCause',
          field: 'stopCause',
          label: `${this.statusList[1].label}原因`,
          align: 'left'
        },
        {
          name: 'duration',
          field: 'duration',
          label: `${this.statusList[1].label}时长`,
          align: 'left'
        },
        {
          name: 'causeUpdateName',
          field: 'causeUpdateName',
          label: '原因修改人',
          align: 'left'
        },
        {
          name: 'remark',
          field: 'remark',
          label: '备注',
          align: 'left'
        }
      ]
      this.isFillIn && tableColumns.push({
        name: 'operate',
        field: 'operate',
        label: '操作',
        align: 'center'
      })
      return tableColumns
    }
  },
  methods: {
    // 非半年之前
    notDisableDate (date) {
      const disableDate = moment(new Date()).startOf('day').subtract(6, 'months')
      const flag = this.isFillIn ? date < new Date(disableDate) : false
      return flag
    },
    getListInit () {
      this.$refs.workShopSearch.getWorkshops().then(() => {
        this.getList()
      })
    },
    // 详情事件
    showEditDialog (data) {
      const info = _.cloneDeep(data)
      Object.keys(info).forEach(key => {
        info[key] = info[key] === '--' ? '' : info[key]
      })
      this.isReports = false
      this.editDetail.data = info
      this.editDetail.show = true
    },
    // 重置
    resetSearch () {
      Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
      this.$refs.workShopSearch.initData()
    },
    // 查询
    onSubmit () {
      this.pagination.pageNum = 1
      this.selectedReport = []
      this.getList()
    },
    // 导出Excel
    onExcel () {
      let data = {
        ...this.cloneParams
      }
      const { location } = this.cloneParams
      data.stopTypeIds = this.cloneParams.stopTypeIds[0] === 'all' ? null : data.stopTypeIds
      data.since = moment(this.cloneParams.dateRange[0]).format('YYYY-MM-DD')
      data.end = moment(this.cloneParams.dateRange[1]).add(1, 'days').format('YYYY-MM-DD')
      data.stopDurationStart = _.isEmpty(this.cloneParams.stopDurationStart) ? this.cloneParams.stopDurationStart : this.cloneParams.stopDurationStart * 60
      data.stopDurationEnd = _.isEmpty(this.cloneParams.stopDurationEnd) ? this.cloneParams.stopDurationEnd : this.cloneParams.stopDurationEnd * 60
      data.deviceTreeReqVO = {
        deviceIds: this.cloneParams.devices[0] !== 'all' ? this.cloneParams.devices : [],
        level: location.level || null,
        schemeId: location.id || null
      }
      data.excelHead = this.tableColumns.map(item => {
        return {
          field: item.field,
          name: item.label
        }
      })
      this.$q.loading.show()
      const params = [{ name: '' }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      data['requestId'] = res.fileNameNew
      this.onSubscribe()
      return getExportExcel(data).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
          this.closeUbscribeTopic()
        }
      }).catch(res => {
        console.log(res)
        this.closeUbscribeTopic()
      })
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.requestId}`)
      this.$q.loading.hide()
    },
    getData (data) {
      return moment(data).format('YYYYMMDD')
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      await this.$saveFileForBlob(msg.data, `${this.getData(this.cloneParams.dateRange[0])}-${this.getData(this.cloneParams.dateRange[1])}机台报表_${this.statusList[1].label}明细统计.xls`)

      this.closeUbscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
    },
    // 批量填报
    onFillin () {
      this.isReports = true
      this.editDetail.show = true
      this.editDetail.data = this.selectedReport[0]
      this.editDetail.selReport = this.selectedReport
    },
    // 获取原因类型列表
    getStopcauseList () {
      return getCauseTypeList(3, true).then(res => {
        if (res.data.length > 0) {
          this.equipmentTypeOptions = [{ label: '全部', id: 'all' }, { label: '空', id: '-1' }, ...res.data]
          this.equipmentTypeOptions.map(v => {
            const item = v
            item.value = v.id
            item.label = v.label
            return item
          })
          this.queryParams.stopTypeIds[0] = 'all'
        }
      })
    },
    //
    getList () {
      this.selectedReport = []
      const params = {
        ...this.queryParams,
        ...this.pagination
      }
      const { location } = this.queryParams
      if (this.isLtTime(this.queryParams.stopDurationStart, this.queryParams.stopDurationEnd)) return
      params.stopDurationStart = _.isEmpty(this.queryParams.stopDurationStart) ? this.queryParams.stopDurationStart : this.queryParams.stopDurationStart * 60
      params.stopDurationEnd = _.isEmpty(this.queryParams.stopDurationEnd) ? this.queryParams.stopDurationEnd : this.queryParams.stopDurationEnd * 60
      params.since = moment(this.queryParams.dateRange[0]).format('YYYY-MM-DD')
      params.end = moment(this.queryParams.dateRange[1]).add(1, 'days').format('YYYY-MM-DD')
      params.stopTypeIds = this.queryParams.stopTypeIds[0] === 'all' || _.isEmpty(this.queryParams.stopTypeIds) ? null : params.stopTypeIds
      params.deviceTreeReqVO = {
        deviceIds: this.queryParams.devices[0] !== 'all' ? this.queryParams.devices : [],
        level: location.level || null,
        schemeId: location.id || null
      }
      this.cloneParams = _.cloneDeep(this.queryParams)
      this.isTableLoading = true
      return getStopStatList(params).then((res) => {
        this.isTableLoading = false
        if (!_.isEmpty(res.data)) {
          const ret = res.data.list
          this.pagination.rowsNumber = res.data.total
          this.tableData = ret.map((v, index) => {
            const item = v
            // 没有数据的字段填充数据为'--'
            Object.keys(item).forEach(key => {
              item[key] = (!item[key] || item[key] === '-') ? '--' : item[key]
            })
            item.startTime = v.startTime && moment(v.startTime).format('YYYY-MM-DD HH:mm:ss')
            item.endTime = v.endTime && moment(v.endTime).format('YYYY-MM-DD HH:mm:ss')
            item.indexId = index
            return item
          })
        }
      }).catch(err => {
        console.log(err)
        this.isTableLoading = false
      })
    },
    isLtTime (lt, ls) {
      if (!_.isNil(lt) && !_.isNil(ls) && Number(lt) > Number(ls)) {
        this.$message.warning('开始时长不得大于结束时长')
        return true
      }
      return false
    }
  },
  mounted () {
    this.getStopcauseList()
    this.getListInit()
  }
}
</script>

<style lang="scss" scoped>
  >>>.z-index {
    z-index: 100
  }
  .stop-stat {
    .for-time {
      line-height: 32px;
      height: 32px;
      text-align: center;
      margin: 0px 6px;
    }
    .btn-time {
      height: 32px;
      max-width: 42px;
    }
    .fontSize-16{
      font-size:16px;
      font-family:PingFang SC;
      font-weight:500;
      color:rgba(51,51,51,1);
    }
  }
</style>
